package view.client;

import model.Hearer;
import view.client.PanelGame;
import view.client.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ConnectException;
import java.net.Socket;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import controller.link.Register;

public class PanelMenu extends JPanel implements ActionListener, Serializable {

    private final static int porta = 2525;
    private String name;
    private String ip;
    private Frame frame;
    private view.server.Console svConsole;

    public PanelMenu(Frame frame) {
        initComponents();
        btnLogin.setEnabled(false); 
        if (frame.isNew){
            btnLogin.setEnabled(true);    
        }        
        try {
            String[] loaded = load();
            this.txtIp.setText(loaded[0]);
            this.txtUser.setText(loaded[1]);
            if (loaded[2].equals("true")) {
                checkOffline.setSelected(true);
                txtIp.setEnabled(false);
            } else if (loaded[2].equals("false")) {
                checkOffline.setSelected(false);
                txtIp.setEnabled(true);
            }
        } catch (IOException ex) {
        } catch (ClassNotFoundException ex) {
        } catch (Exception e) {
        }
        this.frame = frame;
        checkOffline.addActionListener(this);
        btnLogin.addActionListener(this);

        frame.setDefaultButton(btnLogin);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblUser = new javax.swing.JLabel();
        lblIp = new javax.swing.JLabel();
        btnLogin = new javax.swing.JButton();
        txtUser = new javax.swing.JTextField();
        txtIp = new javax.swing.JTextField();
        lblTitulo = new javax.swing.JLabel();
        checkOffline = new javax.swing.JCheckBox();

        setBackground(new java.awt.Color(0, 102, 102));
        setForeground(new java.awt.Color(255, 255, 255));

        lblUser.setForeground(new java.awt.Color(255, 255, 255));
        lblUser.setText("Usuário:");
        lblUser.setName("lblUser"); // NOI18N

        lblIp.setForeground(new java.awt.Color(255, 255, 255));
        lblIp.setText("Ip:");
        lblIp.setName("lblIp"); // NOI18N

        btnLogin.setText("Login");
        btnLogin.setName("btnLogin"); // NOI18N

        txtUser.setMaximumSize(new java.awt.Dimension(6, 20));
        txtUser.setName("txtUser"); // NOI18N

        txtIp.setEnabled(false);
        txtIp.setName("txtIp"); // NOI18N

        lblTitulo.setFont(new java.awt.Font("Tahoma", 0, 24));
        lblTitulo.setForeground(new java.awt.Color(255, 255, 255));
        lblTitulo.setText("CardAdventureConsole v0.59");

        checkOffline.setSelected(true);
        checkOffline.setText("Offline Mode");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblIp)
                                    .addComponent(lblUser))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtIp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
                                    .addComponent(txtUser, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)))
                            .addComponent(lblTitulo)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(467, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(checkOffline, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnLogin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitulo)
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblUser))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblIp))
                .addGap(8, 8, 8)
                .addComponent(checkOffline)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(89, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLogin;
    private javax.swing.JCheckBox checkOffline;
    private javax.swing.JLabel lblIp;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JLabel lblUser;
    private javax.swing.JTextField txtIp;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(getBtnLogin())) {
            String n = txtUser.getText();
            String i = txtIp.getText();
            if (checkOffline.isSelected()) {
                if (svConsole == null) {
                    svConsole = new view.server.Console();
                }
                i = "localhost";
            } else {
                if (!frame.isNew) {
                    JOptionPane.showMessageDialog(null, "Jogo somente disponível offline. Atualize sua versão para jogar online");
                    return;
                }
            }
            if ((!i.equals("")) && (!n.equals(""))) {

                this.name = n;
                this.ip = i;
                try {
                    Socket socket = new Socket(ip, porta);
                    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                    Register r = new Register(name);
                    out.writeObject(r);
                    Object inputServer = in.readObject();
                    if (inputServer instanceof Register) {
                        Register reg = (Register) inputServer;
                        if (reg.isAccepted()) {
                            save();
                            Hearer cliente = new Hearer(socket, in, out, name);
                            frame.loadGame(new PanelGame(cliente, frame));
                            frame.addThread(cliente);
                            cliente.addFrame(frame);
                            System.out.println("Conexão Estabelecida");
                            cliente.start();
                        } else {
                            JOptionPane.showMessageDialog(null, "Usuário já conectado");
                        }

                    }
                } catch (ConnectException ex) {
                    System.out.println("Host " + ip + ":" + porta + " inexistente.");
                    JOptionPane.showMessageDialog(null, "Host Inexistente");
                } catch (Exception ex) {
                    System.out.println("Erro ao conectar");
                    JOptionPane.showMessageDialog(null, "Erro ao Conectar");
                }
            }

        } else if (e.getSource().equals(checkOffline)) {
            if (checkOffline.isSelected()) {
                txtIp.setEnabled(false);
            } else if (!checkOffline.isSelected()) {
                txtIp.setEnabled(true);
            }
        }


    }

    public void save() {
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("configUser.sav"));
            String selected;
            if (checkOffline.isSelected()) {
                selected = "true";
            } else {
                selected = "false";
            }
            String[] obj = {txtIp.getText(), txtUser.getText(), selected};
            oos.writeObject(obj);
            oos.close();
        } catch (IOException ex) {
            //Erro//
        }
    }

    private static String[] load() throws IOException, ClassNotFoundException {
        ObjectInputStream ois =
            new ObjectInputStream(new FileInputStream("configUser.sav"));
        String[] loaded = (String[]) ois.readObject();
        ois.close();
        return loaded;
    }

    public javax.swing.JLabel getLblIp() {
        return lblIp;
    }

    public javax.swing.JLabel getLblTitulo() {
        return lblTitulo;
    }

    public javax.swing.JLabel getLblUser() {
        return lblUser;
    }

    public javax.swing.JButton getBtnLogin() {
        return btnLogin;
    }

    public void setBtnLogin(javax.swing.JButton btnLogin) {
        this.btnLogin = btnLogin;
    }
}
